<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>资金账户管理</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <div class="pageContentWhole">
      <a-row>
        <a-col :span="24">
          <a-form layout="inline">
            <a-form-item label="资金账户">
              <a-input v-model="searchForm.account"></a-input>
            </a-form-item>
            <a-form-item label="币种">
              <a-select v-model="searchForm.currencyType" class="selectWidth">
                <a-select-option key>全部</a-select-option>
                <a-select-option key="CNY">人民币</a-select-option>
                <a-select-option key="USD">美金</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="所属公司">
              <a-tree-select
                class="selectWidth"
                v-model="searchForm.deptId"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :load-data="onLoadData"
                :tree-data="deptTreeData"
              ></a-tree-select>
            </a-form-item>
            <a-form-item label="开户行">
              <a-input v-model="searchForm.bank"></a-input>
            </a-form-item>
            <a-form-item label="状态">
              <a-select v-model="searchForm.status" class="selectWidth">
                <a-select-option key>全部</a-select-option>
                <a-select-option :key="1">正常</a-select-option>
                <a-select-option :key="0">冻结</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item>
              <a-button type="primary" @click="handleSubmit1">查询</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="addItem">+ 创建账户</a-button>
            </a-form-item>
          </a-form>

          <a-table
            :columns="columns"
            :data-source="tableData"
            :loading="loading"
            class="tableMargin"
            :pagination="pagination"
            rowKey="id"
          >
            <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
            <template slot="operation" slot-scope="text, record">
              <a @click="editIt(record)">编辑</a>
              <a @click="detailIt(record.id)">资金明细</a>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </div>

    <!-- 添加/编辑 -->
    <a-modal
      :visible="visible"
      :title="title"
      :confirmLoading="confirmLoading"
      :destroyOnClose="true"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form-model
        ref="rulesForm"
        :model="form"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        :rules="rules"
      >
        <a-form-model-item label="资金账户" prop="account">
          <a-input v-model="form.account" :max-length="50"></a-input>
        </a-form-model-item>
        <a-form-model-item label="币种" prop="currencyType">
          <a-select v-model="form.currencyType">
            <a-select-option key>请选择</a-select-option>
            <a-select-option key="CNY">人民币</a-select-option>
            <a-select-option key="USD">美金</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="所属公司" prop="deptId">
          <a-tree-select
            placeholder="请选择公司"
            v-model="form.deptId"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :load-data="onLoadData"
            :tree-data="deptTreeData"
          ></a-tree-select>
        </a-form-model-item>
        <a-form-model-item label="开户行" prop="bank">
          <a-input v-model="form.bank" :max-length="20"></a-input>
        </a-form-model-item>
        <a-form-model-item label="状态" prop="status">
          <a-select v-model="form.status">
            <a-select-option key>请选择</a-select-option>
            <a-select-option :key="1">正常</a-select-option>
            <a-select-option :key="0">冻结</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { queryDeptList } from '@/api/systemPersonnelManage'
import { queryCompanyCapitalAccountList, addCompanyCapitalAccount, updateCompanyCapitalAccount } from '@/api/financialCenter'

const fomrMessage = `必填项不能为空`
const defaultForm = () => {
  return {
    id: null, // 资金账户id
    account: '',
    currencyType: '', // 币种：CNY、USD
    deptId: '', // 组织架构id
    bank: '', // 开户行
    status: ''
  }
}

export default {
  data () {
    const columns = [
      {
        title: '序号',
        width: 60,
        scopedSlots: { customRender: 'rn' }
      },
      {
        title: '资金账户',
        dataIndex: 'account',
        ellipsis: true
      },
      {
        title: '开户银行',
        dataIndex: 'bank',
        ellipsis: true,
        customRender: (text, row, index) => {
          return text || '--'
        }
      },
      {
        title: '所属公司',
        dataIndex: 'companyName',
        ellipsis: true
      },
      {
        title: '币种',
        dataIndex: 'currencyType',
        customRender: (text, row, index) => {
          return CurrencyType[text]
        }
      },
      {
        title: '当前余额',
        dataIndex: 'balance'
      },
      {
        title: '状态',
        dataIndex: 'status',
        customRender: (text, row, index) => {
          if (text === 1) {
            return <a-badge status="success" text="正常" />
          } else if (text === 0) {
            return <a-badge status="error" text="冻结" />
          }
        }
      },
      {
        title: '操作',
        width: 160,
        scopedSlots: { customRender: 'operation' }
      }
    ]

    const CurrencyType = {
      CNY: '人民币',
      USD: '美元'
    }

    return {
      deptTreeData: [],
      CurrencyType,
      searchForm: {
        account: '', // 资金账户
        currencyType: '', // 币种：CNY、USD
        deptId: '', // 架构id
        bank: '', // 开户行
        status: '' // 状态：1正常，0冻结
      },
      columns,
      tableData: [],
      loading: false,
      pagination: {},
      pageNum: 1,
      pageSize: 10,
      // modal
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      visible: false,
      title: '',
      confirmLoading: false,
      form: defaultForm(),
      rules: {
        deptId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        account: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        currencyType: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        bank: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        status: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }]
      }
    }
  },
  methods: {
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
          resolve()
          return
        }
        queryDeptList({ parentId: treeNode.dataRef.key }).then(rsp => {
          let childrenData = []
          rsp.data.forEach((value) => {
            childrenData.push({
              title: value.name,
              key: value.deptId,
              value: value.deptId,
              isLeaf: true
            })
          })
          treeNode.dataRef.children = childrenData
          this.deptTreeData = [...this.deptTreeData]
          resolve()
        })
      })
    },
    handleSubmit1 () {
      this.pageNum = 1
      this.handleSubmit()
    },
    handleSubmit () {
      this.loading = true
      queryCompanyCapitalAccountList({
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(rsp => {
        this.loading = false
        this.tableData = rsp.data.list
        this.pagination = {
          current: this.pageNum,
          pageSize: rsp.data.pageSize,
          total: rsp.data.total,
          showQuickJumper: false,
          showSizeChanger: true,
          showTotal: total => `共${total}条记录 第${this.pageNum}/${rsp.data.pages}页`,
          onChange: pageNum => {
            this.pageNum = pageNum
            this.handleSubmit()
          },
          onShowSizeChange: (current, size) => {
            this.pageNum = current
            this.pageSize = size
            this.handleSubmit()
          }
        }
      }).catch(() => { this.loading = false })
    },
    // 添加
    addItem () {
      if (!this.$root._bc.createAccount) {
        this.$message.error('您无此权限！')
        return
      }
      this.form = defaultForm()
      this.title = '创建资金账户'
      this.visible = true
    },
    // 编辑
    editIt (item) {
      if (!this.$root._bc.editAccount) {
        this.$message.error('您无此权限！')
        return
      }
      this.form = { ...item }
      this.title = '编辑资金账户'
      this.visible = true
    },
    handleOk () {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          if (!this.form.id) {
            addCompanyCapitalAccount(this.form).then(rsp => {
              this.$message.success('添加成功')
              this.visible = false
              this.handleSubmit()
              setTimeout(() => { this.confirmLoading = false }, 1000)
            }).catch(() => { this.confirmLoading = false })
          } else {
            updateCompanyCapitalAccount(this.form).then(rsp => {
              this.$message.success('编辑成功')
              this.visible = false
              this.handleSubmit()
              setTimeout(() => { this.confirmLoading = false }, 1000)
            }).catch(() => { this.confirmLoading = false })
          }
        }
      })
    },
    handleCancel () {
      this.visible = false
    },
    detailIt (id) {
      this.$router.push('fundAccountManagement/' + id)
    }
  },
  mounted () {
    queryDeptList({ parentId: 0 }).then(rsp => {
      let initData = [{
        title: '全部',
        key: '',
        value: '',
        isLeaf: true
      }]
      rsp.data.forEach((value, index) => {
        initData.push({
          title: value.name,
          key: value.deptId,
          value: value.deptId
        })
      })
      this.deptTreeData = initData

      this.searchForm.deptId = initData[0].key
      this.handleSubmit()
    })
  }
}
</script>

<style lang="less" scoped>
</style>
